/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <string>
#include <unordered_map>
#include <functional>
#include <memory>
#include <mutex>
#include <nlohmann/json.hpp>
#include "web_server.h"
#include "ws_connection.h"

namespace El {
namespace Restful {

class WebSocketConnectionManager {
public:
    static WebSocketConnectionManager &GetInstance();

    // 禁止拷贝和赋值
    WebSocketConnectionManager(const WebSocketConnectionManager &) = delete;
    WebSocketConnectionManager &operator=(const WebSocketConnectionManager &) = delete;

    // 处理WebSocket事件
    std::string ProcessEvent(std::shared_ptr<El::WebServer::WebSocketEvent> &event);

    // 处理WebSocket连接关闭
    void HandleConnectionClosed(int64_t connection_id);

private:
    WebSocketConnectionManager() = default;

    // 获取连接处理器
    std::shared_ptr<WebSocketConnection> GetConnectionHandler(int64_t connection_id);

    // 创建连接处理器
    std::shared_ptr<WebSocketConnection> CreateConnectionHandler(int64_t connection_id);

    // 连接处理器映射表
    std::unordered_map<int64_t, std::shared_ptr<WebSocketConnection>> connection_handlers_;

    // 保护连接处理器映射表的互斥锁
    std::mutex handlers_mutex_;
};

} // namespace Restful
} // namespace El